package cn.minhx.domain.strategy.model.entity;

import cn.hutool.core.collection.CollUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.minhx.types.common.Constants.*;

/**
 * 策略规则实体
 * @author min
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyRuleEntity {

    /** 抽奖策略ID */
    private Long strategyId;
    /** 抽奖奖品ID【规则类型为策略，则不需要奖品ID】 */
    private Long awardId;
    /** 抽象规则类型；1-策略规则、2-奖品规则 */
    private Integer ruleType;
    /** 抽奖规则类型【rule_random - 随机值计算、rule_lock - 抽奖几次后解锁、rule_luck_award - 幸运奖(兜底奖品)】 */
    private String ruleModel;
    /** 抽奖规则比值 */
    private String ruleValue;
    /** 抽奖规则描述 */
    private String ruleDesc;

    public Map<String, List<Long>> getRuleWeightValues() {
        HashMap<String, List<Long>> resultMap = new HashMap<>();
        if (!"rule_weight".equals(ruleModel)) {
            return resultMap;
        }
        String[] ruleValueGroups = ruleValue.split(SPACE);
        for (String ruleValueGroup : ruleValueGroups) {
            if (StringUtils.isBlank(ruleValueGroup)) {
                continue;
            }
            // 分割字符串以获取积分和对应的奖品 - parts[0]:积分 parts[1]:奖品
            String[] parts = ruleValueGroup.split(COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }
            // 解析值
            String[] awardArr = parts[1].split(COMMA);
            List<Long> awardList = CollUtil.newArrayList();
            for (String award : awardArr) {
                awardList.add(Long.valueOf(award));
            }
            resultMap.put(ruleValueGroup, awardList);
        }
        return resultMap;
    }
}
